package com.gomyb.common.base;

import com.gomyb.common.page.PageParam;
import com.gomyb.common.page.PageResult;
import com.gomyb.common.page.QueryFilter;
import com.gomyb.result.JsonResult;
import com.gomyb.result.Result;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.List;

/**
 * @author <a href="mailto:hellohesir@gmail.com">Mr_He</a>
 * 公共controller
 * 返回根对象为Result
 */
public abstract class BaseController<T, ID extends Serializable> {


    protected BaseService<T, ID> service;

    public abstract void setService(BaseService<T, ID> service);

    /**
     * 根据id查询
     */
    protected Result<T> get(ID id) {
        if (null != id) {
            T po = service.get(id);
            if (po != null) {
                return new Result<>(true, po);
            } else {
                return new Result<>("no data...");
            }
        } else {
            return new Result<>("id cannot null...");
        }
    }

    /**
     * 分页条件查询
     */
    protected PageResult<T> findPage(HttpServletRequest request) {
        PageParam pageParam = PageParam.getPageParam(request);
        return service.findPage(pageParam);
    }

    /**
     * 添加一个对象
     */
    protected Result<T> save(T obj) {
        try {
            obj = service.save(obj);
            if (obj != null) {
                return JsonResult.OK(obj);
            } else {
                return JsonResult.NO();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.NO(e.getMessage());
        }
    }

    /**
     * 更新
     */
    protected Result update(T t) {
        return save(t);
    }

    /**
     * 查询全部
     */
    protected Result<List<T>> findAll() {
        List<T> all = service.findAll();
        return new Result<>(true, all);
    }

    /**
     * 条件查询
     */
    protected Result<List<T>> findAll(QueryFilter filter) {
        List<T> all = service.findAll(filter);
        return new Result<>(true, all);
    }

    /**
     * 批量删除
     */
    protected Result deleteAll(String ids) {
        try {
            int count = service.deleteAll(ids);
            if (count > 0) {
                return JsonResult.OK();
            }
        } catch (Exception e) {
            throw new BaseException("删除失败", e);
        }
        return JsonResult.NO();
    }

    protected boolean delete(T t) {
        return service.delete(t);
    }

}
